<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"  %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<form role="form" data-toggle="validator" id="form" name="form" >

<c:set var="docu_type" value="W" />
<c:if test="${not empty productMap}">
	<c:set var="docu_type" value="M" />
	<div id="modal-title" style="display:none;">${productMap.PRD_NAME} (${productMap.PRD_ID})</div>
</c:if>
<input type="hidden" id="docu_type" name="docu_type" value="${docu_type}" />

<div class="row">
	<div class="col-lg-12">
		<div class="panel panel-danger">
			<div class="panel-heading">
            	<i class="glyphicon glyphicon-alert"></i> 안내
			</div>
			<div class="panel-body">
				<div class="row">
					<div class="col-lg-12">
						품목, 색상, 사이즈, 거래처 항목은 <strong>기준코드</strong> 또는 <strong>거래처</strong>를 먼저 등록해야 합니다.
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
		
		<div class="panel panel-default">
			<div class="panel-heading">
            	상품 정보
			</div>
			<div class="panel-body">
				<div class="row">
					<div class="col-lg-4">
					
						<div class="form-group">
						    <label class="control-label">* 상품명</label>
						    <input type="text" class="form-control" id="prd_name" name="prd_name" value="${productMap.PRD_NAME}"
						    										maxlength=32
						    										data-error="상품명을 입력해주세요."
						    										required="required">
						    <div class="help-block with-errors">32자 이내로 작성</div>
						</div>
						
						<div class="form-group">
						   <label class="control-label">* 품목</label>
						   <select class="form-control" id="prd_type" name="prd_type"
						   								data-error="품목을 선택해주세요."
						   								required="required">
						   		<option value="" disabled selected>선택</option>
                               <c:forEach items="${prdTypeList}" var="list">
                               	<option <c:if test="${productMap.PRD_TYPE eq list.CODE}">selected="selected"</c:if> value="${list.CODE}">${list.NAME}</option>
                               </c:forEach>
                           </select>
                           <div class="help-block with-errors">&nbsp;</div>
						</div>
						
						<div class="form-group">
						   <label class="control-label">* 색상</label>
						   <select class="form-control" id="prd_color" name="prd_color"
						   								data-error="색상을 선택해주세요."
						   								required="required">
						   		<option value="" disabled selected>선택</option>
                               <c:forEach items="${prdColorList}" var="list">
                               	<option <c:if test="${productMap.PRD_COLOR eq list.CODE}">selected="selected"</c:if> value="${list.CODE}">${list.NAME}</option>
                               </c:forEach>
                           </select>
                           <div class="help-block with-errors">&nbsp;</div>
						</div>
						
					</div>
					<div class="col-lg-4">
						<div class="form-group">
						   <label class="control-label">* 사이즈 (규격)</label>
						   <select class="form-control" id="prd_size" name="prd_size"
						   								data-error="사이즈를 선택해주세요."
						   								required="required">
						   		<option value="" disabled selected>선택</option>
                               <c:forEach items="${prdSizeList}" var="list">
                               	<option <c:if test="${productMap.PRD_SIZE eq list.CODE}">selected="selected"</c:if> value="${list.CODE}">${list.NAME}</option>
                               </c:forEach>
                           </select>
                           <div class="help-block with-errors">&nbsp;</div>
						</div>
						
						<div class="form-group">
						    <label class="control-label">단가</label>
						    <div class="input-group">
						    	<span class="input-group-addon">￦</span>
							    <input type="text" class="form-control" id="prd_unit_price" name="prd_unit_price" value='<fmt:formatNumber value="${productMap.PRD_UNIT_PRICE}" />'
		 					    										maxlength=12
		 					    										onkeyup="onlyNumber(this);"
		 					    										onblur="onlyNumber(this); comma(this);">
						    </div>
						    <div class="help-block with-errors">반드시 숫자만 입력</div>
						</div>
												
                        <div class="form-group">
							<label class="control-label" id="cus_id_desc">* 거래처 <c:if test="${not empty productMap.PRD_CUSTOMER}">(${productMap.PRD_CUSTOMER})</c:if></label>
							<div class="input-group">
								<span class="input-group-addon"><i class="fa fa-search fa"></i></span>
								<input type="hidden" id="cus_id" name="cus_id" value="${productMap.CUS_ID}" />
								<input type="hidden" id="cus_name_match" name="cus_name_match" value="${productMap.CUS_NAME}" />
	                            <input type="text" class="form-control" id="cus_name" name="cus_name" value="${productMap.CUS_NAME}"
	                            										data-provide="typeahead" 
	                            										data-error="거래처를 선택해주세요."
	                            										data-match="#cus_name_match"
	                            										data-match-error="거래처를 선택해주세요."
	                            										<c:if test="${not empty productMap}">readonly="readonly"</c:if>
	                            										required="required">
							</div>                            
                            <span class="help-block with-errors">거래처를 선택(자동완성)</span>
                        </div>
					</div>
					<div class="col-lg-4">
						<div class="form-group">
						    <label class="control-label">* 상품 ID</label>
						    <input type="text" class="form-control" id="prd_id" name="prd_id" placeholder="자동 생성" value="${productMap.PRD_ID}"
						    										readonly="readonly">
						    <div class="help-block with-errors">등록시 자동 생성</div>
						</div>
							
						<div class="form-group">
							<label>메모</label>
							<textarea class="form-control" id="memo" name="memo" style="height:133px;">${productMap.MEMO}</textarea>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<div class="row">
	<div class="col-lg-12" style="text-align:center;">
		<c:choose>
			<c:when test="${empty productMap}">
				<button type="submit" class="btn btn-success" 
									  data-toggle="confirmation" 
									  title="<spring:message code='comm.write.confirm' />" 
									  data-btn-ok-label="<spring:message code='comm.btn.continue' />"
									  data-btn-cancel-label="<spring:message code='comm.btn.cancle' />">등록</button>
			</c:when>
			<c:otherwise>
				<button type="submit" class="btn btn-primary"
									  data-toggle="confirmation" 
									  title="<spring:message code='comm.modify.confirm' />" 
									  data-btn-ok-label="<spring:message code='comm.btn.continue' />"
									  data-btn-cancel-label="<spring:message code='comm.btn.cancle' />">수정</button>
				<button type="button" class="btn btn-default" data-dismiss="modal">닫기</button>
			</c:otherwise>
		</c:choose>
	</div>
</div>
		
</form>
				


<script type="text/javascript">
	
	$('[data-toggle=confirmation]').confirmation();
	
	$('#cus_name').confirmation({
		title : '거래처를 변경하시겠습니까?'
		,trigger : 'manual'
		,btnOkLabel : '<i class="icon-ok-sign icon-white"></i> 예'
		,btnCancelLabel : '<i class="icon-remove-sign"></i> 아니오'
		,onConfirm : function(){
			$('#cus_name').attr("readonly", false);
			$('#cus_name').val("");
			$('#cus_id').val("");
			$('#cus_id_desc').html("* 거래처");
			$('#cus_name').confirmation('toggle');
		}
	});
	
	$('#cus_name').on('click', function() {
		
		if ($('#cus_name').attr("readonly")) {
			$('#cus_name').confirmation('toggle');
		} 
		
	});
	
	$(document).ready(function() {
		
		$('#cus_name').typeahead({
			minLength: 2
		   ,source: function (query, process) {
		        return $.ajax({
		            url: '/customer/searchCustomer.json',
		            type: 'post',
		            data: { keyword: query },
		            dataType: 'json',
		            success: function (result) {
		                var resultList = result.map(function (item) {
		                    var aItem = { id: item.ID, name: item.VALUE };
		                    return JSON.stringify(aItem);
		                });

		                return process(resultList);

		            }
		        });
		    } 

			,matcher: function (obj) {
		        var item = JSON.parse(obj);
		        return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
		    }

		    ,sorter: function (items) {          
		       var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
		        while (aItem = items.shift()) {
		            var item = JSON.parse(aItem);
		            if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
		            else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
		            else caseInsensitive.push(JSON.stringify(item));
		        }

		        return beginswith.concat(caseSensitive, caseInsensitive)

		    }


		    ,highlighter: function (obj) {
		        var item = JSON.parse(obj);
		        var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
		        return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
		            return '<strong>' + match + '</strong>'
		        })
		    }

		   ,updater: function (obj) {
		        var item = JSON.parse(obj);
		        $('#cus_id').val(item.id);
		        $('#cus_id_desc').html("* 거래처 : <strong>" + item.id + "</strong>");
		        $('#cus_name_match').val(item.name);
		        $('#cus_name').attr('readonly', true);
		        return item.name;
		    }
		});
		
		
		$('#form').validator().on('submit', function(e) {
			
			if (e.isDefaultPrevented()) {
				bs_alert.modal("<spring:message code='comm.field.empty.error' />", "info");
			} else {
				
				e.preventDefault();
				
				var url = "/product/submitRegister.ur";
				var action_flag = "RELOAD";
				<c:if test="${not empty productMap}">
					url = "/product/submitModify.ur";
					action_flag = "LIST";
				</c:if>
					
				$.ajax({
			        url: url,
			        type: "POST",
			        data: $(this).serializeArray(),
			        success: function(data, status, xhr) {
						switch(data) {
							case 0 : 
								bs_alert.modal("<spring:message code='comm.modify.success' />", "success", action_flag);
								break;
							case 9 : 
								bs_alert.modal("<spring:message code='comm.request.data.error' />", "warning", action_flag);
								break;
							case 1 :
								bs_alert.modal("<spring:message code='comm.db.modify.error' />", 'warning', action_flag);
								break;
							case 8 :
								bs_alert.modal("<spring:message code='comm.unknown.error' />", 'warning', action_flag);
								break;
						}
			        },
			        error: function(xhr, status, err) {
			            // do the error stuff
			        }
			    });
				
			}
		});
	});
	
	
</script>